package org.lewis.demo.service.impl;

import org.lewis.demo.entity.SysUser;
import org.lewis.demo.repo.UserRepository;
import org.lewis.demo.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<SysUser> init(String prefix, Integer count) {
        List<SysUser> list = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            String name = String.format("%s-%d", prefix, i);
            list.add(new SysUser(name, new Date()));
        }
        return this.userRepository.saveAll(list);
    }

    @Override
    public long count() {
        return this.userRepository.count();
    }

    @Cacheable(cacheNames = "users", key = "#name")
    @Override
    public SysUser findByName(String name) {
        return this.userRepository.findByName(name);
    }

    @CachePut(cacheNames = "users", key = "#name")
    @Override
    public SysUser update(String name, String birth) {
        SysUser user = this.userRepository.findByName(name);
        user.setBirth(Date.from(
                LocalDate.parse(birth, DateTimeFormatter.ISO_LOCAL_DATE)
                        .atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()
        ));
        return this.userRepository.save(user);
    }

    @CacheEvict(cacheNames = "users", key = "#name")
    @Transactional
    @Override
    public void delete(String name) {
        this.userRepository.deleteByName(name);
    }

}
